/*
 * 🤖 AIOT智能学习桌主控程序 - 完整版
 *
 * 功能模块：
 * ✅ 开机启动音乐和欢迎界面
 * ✅ 超声波坐姿监测系统 (距离检测 + AI语音提醒)
 * ✅ 智能语音交互系统 (小助手AI对话)
 * ✅ 摄像头坐姿检测模块 (AI智能分析)
 * ✅ 整点时间提醒 (蜂鸣器音乐 + 语音播报 + OLED显示)
 * ✅ 数据存储和微信小程序同步
 * ✅ 系统关机和数据备份
 *
 * 硬件配置：EBP3901开发板 + 各种传感器
 *
 * 作者：AIOT智能学习桌项目组
 * 版本：v2.0 完整功能版
 */

// ========== 库文件引入 ==========
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <WebSocketsClient.h>
#include <time.h>
#include <esp_now.h>

// ========== 硬件引脚配置 (基于EBP3901实际接线) ==========
// OLED显示屏 (I2C) - J12接口
#define OLED_SDA_PIN 21 // J12引脚3 (I2C1_SDA)
#define OLED_SCL_PIN 22 // J12引脚5 (I2C1_SCL)
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C

// 超声波传感器 (HC-SR04) - J12接口
#define TRIG_PIN 28 // J12引脚11 (GPIO28)
#define ECHO_PIN 29 // J12引脚12 (GPIO29)

// 蜂鸣器控制 - J12接口
#define BUZZER_PIN 42 // J12引脚32 (GPIO42) PWM控制

// WiFi模块 (ESP8266) - J12接口
#define WIFI_RX_PIN 10 // J12引脚10 (UART5_RX)
#define WIFI_TX_PIN 8  // J12引脚8 (UART5_TX)

// 音频模块 - J10 PMOD接口
#define AUDIO_OUT_PIN 25 // J10引脚3 (GPIO25) 音频输出

// 按键输入 - J12接口
#define BUTTON_FUNC_PIN 56  // J12引脚29 (GPIO56) 功能按键
#define BUTTON_CALIB_PIN 82 // J12引脚31 (GPIO82) 校准按键
#define BUTTON_RESET_PIN 83 // J12引脚37 (GPIO83) 复位按键

// LED指示灯 - J12接口
#define LED_RED_PIN 35   // J12引脚16 (GPIO35) 红色LED
#define LED_GREEN_PIN 36 // J12引脚18 (GPIO36) 绿色LED
#define LED_BLUE_PIN 41  // J12引脚22 (GPIO41) 蓝色LED

// 继电器控制 - J12接口
#define RELAY_PIN 52 // J12引脚33 (GPIO52) 继电器控制

// 光敏传感器 - J2 PMOD接口
#define LIGHT_SENSOR_PIN A0 // J2引脚7 (GPIO83) 模拟输入

// 麦克风模块 - J2 PMOD接口
#define MIC_INPUT_PIN A1 // J2引脚8 (GPIO85) 麦克风输入

// ========== 全局对象初始化 ==========
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
SoftwareSerial wifiSerial(WIFI_RX_PIN, WIFI_TX_PIN);
HTTPClient httpClient;
WebSocketsClient webSocket;

// ========== 系统配置参数 ==========
// 坐姿监测参数
const float IDEAL_DISTANCE_MIN = 30.0;   // 理想距离最小值(cm)
const float IDEAL_DISTANCE_MAX = 50.0;   // 理想距离最大值(cm)
const float WARNING_DISTANCE_MIN = 20.0; // 警告距离最小值(cm)
const float WARNING_DISTANCE_MAX = 70.0; // 警告距离最大值(cm)

// 时间间隔参数
const unsigned long POSTURE_CHECK_INTERVAL = 3000;  // 3秒检查一次坐姿
const unsigned long DISPLAY_UPDATE_INTERVAL = 1000; // 1秒更新一次显示
const unsigned long HOUR_INTERVAL = 3600000;        // 1小时整点提醒
const unsigned long DATA_SAVE_INTERVAL = 600000;    // 10分钟保存一次数据
const unsigned long WARNING_INTERVAL = 30000;       // 30秒内不重复警告

// WiFi和API配置
const char *WIFI_SSID = "YourWiFiName";                                // 替换为实际WiFi名称
const char *WIFI_PASSWORD = "YourPassword";                            // 替换为实际WiFi密码
const char *WECHAT_API_URL = "https://your-api.com/wechat";            // 微信小程序API
const char *AI_API_URL = "https://api.openai.com/v1/chat/completions"; // AI API
const char *AI_API_KEY = "your-openai-api-key";                        // 替换为实际API密钥

// ========== 系统状态结构体 ==========
struct SystemState
{
  // 坐姿监测状态
  float currentDistance;
  bool isUserPresent;
  String postureStatus;
  int postureWarnings;
  unsigned long lastWarningTime;

  // 系统状态
  unsigned long sessionStartTime;
  unsigned long totalStudyTime;
  bool wifiConnected;
  bool voiceEnabled;
  bool cameraEnabled;

  // 时间状态
  String currentTime;
  int currentHour;
  int currentMinute;
  unsigned long lastHourlyReminder;

  // 数据统计
  int totalSessions;
  float averagePostureScore;
  int dailyWarnings;
  String lastUserQuestion;
} systemState;

// 坐姿历史数据
struct PostureRecord
{
  float distance;
  String status;
  String aiSuggestion;
  unsigned long timestamp;
  float score;
} postureHistory[20]; // 存储最近20次记录

// AI语音交互缓存
struct VoiceCache
{
  String lastQuestion;
  String lastResponse;
  unsigned long lastInteractionTime;
  int interactionCount;
} voiceCache;

// 时间控制变量
unsigned long lastPostureCheck = 0;
unsigned long lastDisplayUpdate = 0;
unsigned long lastDataSave = 0;

// 音符频率定义 (完整音阶)
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784

// ========== 系统初始化 ==========
void setup()
{
  Serial.begin(115200);
  Serial.println("🤖 AIOT智能学习桌系统启动中...");

  // 硬件初始化
  initializePins();
  initializeDisplay();
  initializeWiFi();
  initializeAudioSystem();
  initializeTimeSystem();

  // 显示启动画面
  showBootScreen();

  // 播放开机音乐
  playStartupMelody();

  // 语音欢迎
  speakMessage("欢迎使用智能学习桌，祝您学习愉快！");

  // 初始化系统状态
  initializeSystemState();

  // 连接微信小程序
  connectToWeChatMiniProgram();

  Serial.println("✅ 智能学习桌系统启动完成！");
  setLEDStatus("ready"); // 绿色LED表示就绪
  delay(2000);
}

// ========== 主控制循环 ==========
void loop()
{
  unsigned long currentTime = millis();

  // 🔍 坐姿监测系统 (每3秒检查一次)
  if (currentTime - lastPostureCheck >= POSTURE_CHECK_INTERVAL)
  {
    performPostureAnalysis();
    lastPostureCheck = currentTime;
  }

  // 📺 显示更新 (每1秒更新一次)
  if (currentTime - lastDisplayUpdate >= DISPLAY_UPDATE_INTERVAL)
  {
    updateMainDisplay();
    updateTimeDisplay();
    lastDisplayUpdate = currentTime;
  }

  // ⏰ 整点时间提醒
  checkHourlyReminder();

  // 💾 数据存储和同步 (每10分钟)
  if (currentTime - lastDataSave >= DATA_SAVE_INTERVAL)
  {
    saveSessionData();
    syncWithWeChatMiniProgram();
    lastDataSave = currentTime;
  }

  // 📡 处理WiFi通信和小程序消息
  handleWiFiCommunication();

  // 🎤 处理语音交互
  handleVoiceInteraction();

  // 📸 处理摄像头坐姿检测
  handleCameraDetection();

  // 🔘 处理按键输入
  handleButtonInputs();

  // 💡 环境光线自动调节
  handleLightingControl();

  delay(100); // 主循环延时
}

// ========== 硬件初始化函数 ==========
void initializePins()
{
  // 配置输出引脚
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_RED_PIN, OUTPUT);
  pinMode(LED_GREEN_PIN, OUTPUT);
  pinMode(LED_BLUE_PIN, OUTPUT);
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(AUDIO_OUT_PIN, OUTPUT);

  // 配置输入引脚
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUTTON_FUNC_PIN, INPUT_PULLUP);
  pinMode(BUTTON_CALIB_PIN, INPUT_PULLUP);
  pinMode(BUTTON_RESET_PIN, INPUT_PULLUP);
  pinMode(LIGHT_SENSOR_PIN, INPUT);
  pinMode(MIC_INPUT_PIN, INPUT);

  // 初始化输出状态
  digitalWrite(TRIG_PIN, LOW);
  digitalWrite(LED_RED_PIN, LOW);
  digitalWrite(LED_GREEN_PIN, LOW);
  digitalWrite(LED_BLUE_PIN, LOW);
  digitalWrite(RELAY_PIN, LOW);

  Serial.println("✅ 硬件引脚初始化完成");
}

bool initializeDisplay()
{
  Wire.begin(OLED_SDA_PIN, OLED_SCL_PIN);

  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS))
  {
    Serial.println("❌ OLED显示屏初始化失败！");
    return false;
  }

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  Serial.println("✅ OLED显示屏初始化完成");
  return true;
}

void initializeWiFi()
{
  wifiSerial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("🌐 正在连接WiFi");
  while (WiFi.status() != WL_CONNECTED && millis() < 20000)
  {
    delay(500);
    Serial.print(".");
  }

  if (WiFi.status() == WL_CONNECTED)
  {
    systemState.wifiConnected = true;
    Serial.println("\n✅ WiFi连接成功");
    Serial.print("📶 IP地址: ");
    Serial.println(WiFi.localIP());
  }
  else
  {
    systemState.wifiConnected = false;
    Serial.println("\n❌ WiFi连接失败");
  }
}

void initializeAudioSystem()
{
  // 配置音频输出PWM
  ledcSetup(0, 5000, 8); // 通道0，5kHz频率，8位分辨率
  ledcAttachPin(AUDIO_OUT_PIN, 0);

  Serial.println("✅ 音频系统初始化完成");
}

void initializeTimeSystem()
{
  // 配置时间服务器
  configTime(8 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  // 等待时间同步
  Serial.print("⏰ 正在同步网络时间");
  int attempts = 0;
  while (!time(nullptr) && attempts < 10)
  {
    delay(1000);
    Serial.print(".");
    attempts++;
  }

  if (time(nullptr))
  {
    Serial.println("\n✅ 网络时间同步成功");
  }
  else
  {
    Serial.println("\n⚠️ 网络时间同步失败，使用本地计时");
  }
}

void initializeSystemState()
{
  systemState.currentDistance = 0;
  systemState.isUserPresent = false;
  systemState.postureStatus = "未检测";
  systemState.postureWarnings = 0;
  systemState.lastWarningTime = 0;

  systemState.sessionStartTime = millis();
  systemState.totalStudyTime = 0;
  systemState.voiceEnabled = true;
  systemState.cameraEnabled = true;

  systemState.currentTime = getCurrentTimeString();
  systemState.currentHour = getHour();
  systemState.currentMinute = getMinute();
  systemState.lastHourlyReminder = 0;

  systemState.totalSessions = 0;
  systemState.averagePostureScore = 0;
  systemState.dailyWarnings = 0;
  systemState.lastUserQuestion = "";

  voiceCache.lastQuestion = "";
  voiceCache.lastResponse = "";
  voiceCache.lastInteractionTime = 0;
  voiceCache.interactionCount = 0;

  // 从EEPROM加载历史数据
  loadHistoryData();

  Serial.println("✅ 系统状态初始化完成");
}

// ========== 坐姿监测系统 ==========
void performPostureAnalysis()
{
  // 超声波距离检测
  float distance = measureUltrasonicDistance();
  systemState.currentDistance = distance;

  // 判断用户是否在座
  if (distance > 0 && distance < 200)
  {
    systemState.isUserPresent = true;

    // AI坐姿分析
    PostureAnalysisResult result = analyzePostureWithAI(distance);
    systemState.postureStatus = result.status;

    // 记录坐姿数据
    recordPostureData(distance, result.status, result.suggestion, result.score);

    // 检查是否需要语音提醒
    if (result.needsWarning && shouldGiveWarning())
    {
      givePostureWarning(result.status, distance, result.suggestion);
    }

    // 发送数据到摄像头模块进行联合分析
    requestCameraPostureAnalysis();
  }
  else
  {
    systemState.isUserPresent = false;
    systemState.postureStatus = "离座";
  }

  Serial.printf("📏 距离: %.1fcm | 状态: %s | 用户在座: %s\n",
                distance, systemState.postureStatus.c_str(),
                systemState.isUserPresent ? "是" : "否");
}

float measureUltrasonicDistance()
{
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH, 30000); // 30ms超时

  if (duration == 0)
  {
    return -1; // 测量失败
  }

  float distance = duration * 0.034 / 2;
  return distance;
}

struct PostureAnalysisResult
{
  String status;
  String suggestion;
  float score;
  bool needsWarning;
};

PostureAnalysisResult analyzePostureWithAI(float distance)
{
  PostureAnalysisResult result;

  // 基于距离的AI分析逻辑
  if (distance >= IDEAL_DISTANCE_MIN && distance <= IDEAL_DISTANCE_MAX)
  {
    result.status = "优秀";
    result.suggestion = "坐姿很好，继续保持";
    result.score = 95.0;
    result.needsWarning = false;
  }
  else if (distance < WARNING_DISTANCE_MIN)
  {
    result.status = "过近";
    result.suggestion = "请向后移动座椅，距离屏幕" + String(IDEAL_DISTANCE_MIN) + "到" + String(IDEAL_DISTANCE_MAX) + "厘米最佳";
    result.score = 30.0;
    result.needsWarning = true;
  }
  else if (distance > WARNING_DISTANCE_MAX)
  {
    result.status = "过远";
    result.suggestion = "请向前调整座椅，保持合适的学习距离";
    result.score = 40.0;
    result.needsWarning = true;
  }
  else if (distance < IDEAL_DISTANCE_MIN)
  {
    result.status = "稍近";
    result.suggestion = "轻微向后调整一下位置";
    result.score = 70.0;
    result.needsWarning = true;
  }
  else
  {
    result.status = "稍远";
    result.suggestion = "轻微向前调整一下位置";
    result.score = 75.0;
    result.needsWarning = true;
  }

  return result;
}

bool shouldGiveWarning()
{
  unsigned long currentTime = millis();
  return (currentTime - systemState.lastWarningTime) >= WARNING_INTERVAL;
}

void givePostureWarning(String status, float distance, String suggestion)
{
  systemState.lastWarningTime = millis();
  systemState.postureWarnings++;
  systemState.dailyWarnings++;

  // 播放警告音
  playWarningBeep();

  // AI语音提醒
  String voiceMessage = generateAIVoiceReminder(status, distance, suggestion);
  speakMessage(voiceMessage);

  // 设置LED状态
  setLEDStatus("warning");

  // 发送警告到微信小程序
  sendPostureAlertToWeChat(status, distance, suggestion);

  Serial.println("⚠️ 坐姿警告: " + voiceMessage);
}

String generateAIVoiceReminder(String status, float distance, String suggestion)
{
  String baseMessage = "检测到坐姿" + status + "，当前距离" + String(distance, 1) + "厘米。";

  // AI增强建议
  if (status == "过近")
  {
    return baseMessage + "长时间近距离用眼会导致视力下降，" + suggestion + "，保护您的视力健康。";
  }
  else if (status == "过远")
  {
    return baseMessage + "距离过远会影响学习效率，" + suggestion + "，找到最舒适的学习位置。";
  }
  else
  {
    return baseMessage + suggestion + "，让我们一起维持良好的学习姿态。";
  }
}

void recordPostureData(float distance, String status, String suggestion, float score)
{
  // 移动历史数据
  for (int i = 18; i >= 0; i--)
  {
    postureHistory[i + 1] = postureHistory[i];
  }

  // 记录新数据
  postureHistory[0].distance = distance;
  postureHistory[0].status = status;
  postureHistory[0].aiSuggestion = suggestion;
  postureHistory[0].timestamp = millis();
  postureHistory[0].score = score;

  // 更新平均分数
  float totalScore = 0;
  int validRecords = 0;
  for (int i = 0; i < 20; i++)
  {
    if (postureHistory[i].timestamp > 0)
    {
      totalScore += postureHistory[i].score;
      validRecords++;
    }
  }
  if (validRecords > 0)
  {
    systemState.averagePostureScore = totalScore / validRecords;
  }
}

// ========== 智能语音交互系统 ==========
void handleVoiceInteraction()
{
  // 检测麦克风输入
  int micLevel = analogRead(MIC_INPUT_PIN);

  // 简单的声音检测阈值
  if (micLevel > 512)
  {             // 检测到声音
    delay(100); // 防抖

    // 模拟语音识别过程
    String recognizedText = simulateVoiceRecognition();

    if (recognizedText.length() > 0)
    {
      processVoiceCommand(recognizedText);
    }
  }

  // 处理来自微信小程序的语音消息
  handleWeChatVoiceMessage();
}

String simulateVoiceRecognition()
{
  // 在实际项目中，这里应该调用语音识别API
  // 现在返回一些模拟的识别结果用于测试
  static int testCounter = 0;
  testCounter++;

  String testCommands[] = {
      "小助手，现在几点了？",
      "小助手，我的坐姿怎么样？",
      "小助手，今天学习了多长时间？",
      "小助手，给我一些学习建议",
      "" // 大部分时候返回空字符串
  };

  if (testCounter % 100 == 0)
  { // 偶尔模拟识别到语音
    return testCommands[random(0, 4)];
  }

  return "";
}

void processVoiceCommand(String command)
{
  command.toLowerCase();
  voiceCache.lastQuestion = command;
  voiceCache.lastInteractionTime = millis();
  voiceCache.interactionCount++;

  Serial.println("🎤 识别到语音: " + command);

  String response = "";

  if (command.indexOf("小助手") >= 0)
  {
    if (command.indexOf("时间") >= 0 || command.indexOf("几点") >= 0)
    {
      response = "现在时间是" + getCurrentTimeString() + "，您已经学习了" +
                 String((millis() - systemState.sessionStartTime) / 60000) + "分钟。";
    }
    else if (command.indexOf("坐姿") >= 0)
    {
      response = generatePostureStatusReport();
    }
    else if (command.indexOf("学习时间") >= 0 || command.indexOf("学习了多长时间") >= 0)
    {
      unsigned long studyMinutes = (millis() - systemState.sessionStartTime) / 60000;
      response = "今天您已经学习了" + String(studyMinutes) + "分钟，坐姿提醒" +
                 String(systemState.postureWarnings) + "次，平均坐姿得分" +
                 String(systemState.averagePostureScore, 1) + "分。";
    }
    else if (command.indexOf("建议") >= 0 || command.indexOf("帮助") >= 0)
    {
      response = generateAILearningAdvice();
    }
    else
    {
      // 调用AI API获取智能回复
      response = getAIResponse(command);
    }

    voiceCache.lastResponse = response;
    speakMessage(response);

    // 发送交互记录到微信小程序
    sendVoiceInteractionToWeChat(command, response);
  }

  Serial.println("🤖 AI回复: " + response);
}

String generatePostureStatusReport()
{
  String report = "当前坐姿状态：" + systemState.postureStatus +
                  "，距离" + String(systemState.currentDistance, 1) + "厘米";

  if (systemState.averagePostureScore >= 90)
  {
    report += "。您的坐姿非常棒，请继续保持！";
  }
  else if (systemState.averagePostureScore >= 70)
  {
    report += "。坐姿总体良好，注意偶尔调整一下。";
  }
  else
  {
    report += "。建议您更加注意坐姿，保护身体健康。";
  }

  return report;
}

String generateAILearningAdvice()
{
  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;

  String advice = "";
  if (studyTime < 30)
  {
    advice = "刚开始学习，建议您调整好坐姿，保持专注。记住每隔25分钟休息5分钟，这样学习效率更高。";
  }
  else if (studyTime < 60)
  {
    advice = "学习状态不错！建议您起身活动一下，眺望远方放松眼睛，然后继续保持这种专注状态。";
  }
  else
  {
    advice = "学习时间较长了，建议您休息10-15分钟，做些伸展运动，喝点水补充能量，劳逸结合才能持续高效学习。";
  }

  return advice;
}

String getAIResponse(String question)
{
  if (!systemState.wifiConnected)
  {
    return "网络连接中断，暂时无法提供智能回复，请检查网络连接。";
  }

  // 构建AI API请求
  HTTPClient http;
  http.begin(AI_API_URL);
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Authorization", "Bearer " + String(AI_API_KEY));

  // 构建请求体
  String payload = "{";
  payload += "\"model\":\"gpt-3.5-turbo\",";
  payload += "\"messages\":[";
  payload += "{\"role\":\"system\",\"content\":\"你是一个智能学习桌的AI助手，专门帮助用户提高学习效率和保持健康姿态。请用简洁友好的语言回复。\"},";
  payload += "{\"role\":\"user\",\"content\":\"" + question + "\"}";
  payload += "],";
  payload += "\"max_tokens\":100,";
  payload += "\"temperature\":0.7";
  payload += "}";

  int httpResponseCode = http.POST(payload);
  String response = "抱歉，暂时无法连接到AI服务，请稍后再试。";

  if (httpResponseCode == 200)
  {
    String responseBody = http.getString();
    // 解析JSON响应（简化版）
    int contentStart = responseBody.indexOf("\"content\":\"") + 11;
    int contentEnd = responseBody.indexOf("\"", contentStart);
    if (contentStart > 10 && contentEnd > contentStart)
    {
      response = responseBody.substring(contentStart, contentEnd);
    }
  }

  http.end();
  return response;
}

// ========== 摄像头坐姿检测集成 ==========
void handleCameraDetection()
{
  // 通过串口与摄像头检测模块通信
  static unsigned long lastCameraCheck = 0;

  if (millis() - lastCameraCheck >= 5000)
  { // 每5秒请求一次摄像头分析
    requestCameraPostureAnalysis();
    lastCameraCheck = millis();
  }

  // 处理来自摄像头模块的检测结果
  if (Serial.available())
  {
    String cameraData = Serial.readStringUntil('\n');
    processCameraDetectionResult(cameraData);
  }
}

void requestCameraPostureAnalysis()
{
  if (!systemState.cameraEnabled)
    return;

  // 发送请求到摄像头检测模块
  Serial.println("CAMERA_REQUEST:" + String(systemState.currentDistance));
}

void processCameraDetectionResult(String data)
{
  if (!data.startsWith("CAMERA_RESULT:"))
    return;

  String result = data.substring(14); // 移除前缀

  // 解析摄像头检测结果 (JSON格式)
  // 格式示例: {"posture":"good","head_tilt":5,"shoulder_level":3,"suggestions":"保持当前姿态"}

  int postureStart = result.indexOf("\"posture\":\"") + 11;
  int postureEnd = result.indexOf("\"", postureStart);
  String cameraPosture = result.substring(postureStart, postureEnd);

  int suggestionStart = result.indexOf("\"suggestions\":\"") + 15;
  int suggestionEnd = result.indexOf("\"", suggestionStart);
  String cameraSuggestions = result.substring(suggestionStart, suggestionEnd);

  // 融合超声波和摄像头检测结果
  String combinedAnalysis = combinePostureAnalysis(systemState.postureStatus, cameraPosture);
  String enhancedSuggestions = enhancePostureSuggestions(cameraSuggestions);

  // 如果摄像头检测到严重问题，立即给出语音提醒
  if (cameraPosture == "poor" || cameraPosture == "slouching")
  {
    speakMessage("摄像头检测到您" + enhancedSuggestions + "，请及时调整。");
    setLEDStatus("camera_warning");
  }

  Serial.println("📸 摄像头检测: " + cameraPosture + " | 建议: " + cameraSuggestions);
}

String combinePostureAnalysis(String ultrasonicResult, String cameraResult)
{
  // 融合两种检测方式的结果
  if (ultrasonicResult == "优秀" && cameraResult == "good")
  {
    return "完美";
  }
  else if (ultrasonicResult == "过近" || ultrasonicResult == "过远")
  {
    return ultrasonicResult; // 距离问题优先
  }
  else if (cameraResult == "poor" || cameraResult == "slouching")
  {
    return "姿态异常";
  }
  else
  {
    return "良好";
  }
}

String enhancePostureSuggestions(String cameraSuggestions)
{
  // 基于摄像头分析结果提供更详细的建议
  if (cameraSuggestions.indexOf("头部") >= 0)
  {
    return "头部姿态需要调整，" + cameraSuggestions;
  }
  else if (cameraSuggestions.indexOf("肩膀") >= 0)
  {
    return "肩膀位置不佳，" + cameraSuggestions;
  }
  else if (cameraSuggestions.indexOf("背部") >= 0)
  {
    return "背部挺直度不够，" + cameraSuggestions;
  }
  else
  {
    return cameraSuggestions;
  }
}

// ========== 整点时间提醒系统 ==========
void checkHourlyReminder()
{
  int currentHour = getHour();
  int currentMinute = getMinute();

  // 检查是否到达整点
  if (currentMinute == 0 && currentHour != systemState.currentHour)
  {
    if (millis() - systemState.lastHourlyReminder >= 3600000)
    { // 确保每小时只提醒一次
      performHourlyReminder();
      systemState.lastHourlyReminder = millis();
      systemState.currentHour = currentHour;
    }
  }
}

void performHourlyReminder()
{
  Serial.println("⏰ 整点时间提醒");

  // 播放整点音乐
  playHourlyChime();

  // 语音播报时间和学习统计
  String timeAnnouncement = generateTimeAnnouncement();
  speakMessage(timeAnnouncement);

  // OLED显示特别提醒界面
  showHourlyReminderDisplay();

  // 发送整点提醒到微信小程序
  sendHourlyReminderToWeChat();

  // LED闪烁提示
  blinkLEDs();
}

String generateTimeAnnouncement()
{
  String timeStr = getCurrentTimeString();
  unsigned long studyMinutes = (millis() - systemState.sessionStartTime) / 60000;

  String announcement = "现在时间" + timeStr + "。";

  if (studyMinutes > 60)
  {
    announcement += "您已经连续学习了" + String(studyMinutes) + "分钟，";
    announcement += "建议您起身休息一下，眺望远方，保护视力健康。";
  }
  else
  {
    announcement += "学习状态良好，请继续保持专注。";
  }

  if (systemState.postureWarnings > 0)
  {
    announcement += "今日坐姿提醒" + String(systemState.dailyWarnings) + "次，注意保持良好坐姿。";
  }

  return announcement;
}

void showHourlyReminderDisplay()
{
  display.clearDisplay();

  // 标题
  display.setTextSize(2);
  display.setCursor(10, 5);
  display.println("整点提醒");

  // 当前时间
  display.setTextSize(1);
  display.setCursor(0, 25);
  display.print("时间: ");
  display.println(getCurrentTimeString());

  // 学习统计
  unsigned long studyMinutes = (millis() - systemState.sessionStartTime) / 60000;
  display.setCursor(0, 35);
  display.print("学习: ");
  display.print(studyMinutes);
  display.println(" 分钟");

  display.setCursor(0, 45);
  display.print("坐姿: ");
  display.print(systemState.postureStatus);
  display.print(" (");
  display.print(systemState.averagePostureScore, 0);
  display.println("分)");

  display.setCursor(0, 55);
  display.println("注意休息，保护视力");

  display.display();

  delay(5000); // 显示5秒
}

// ========== 数据存储和微信小程序同步 ==========
void saveSessionData()
{
  Serial.println("💾 保存会话数据");

  // 保存到EEPROM
  saveToEEPROM();

  // 生成会话报告
  String sessionReport = generateSessionReport();

  // 发送到微信小程序
  if (systemState.wifiConnected)
  {
    sendSessionDataToWeChat(sessionReport);
  }

  Serial.println("✅ 数据保存完成");
}

void saveToEEPROM()
{
  int address = 0;

  // 保存基本统计数据
  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;
  EEPROM.put(address, studyTime);
  address += sizeof(studyTime);

  EEPROM.put(address, systemState.postureWarnings);
  address += sizeof(systemState.postureWarnings);

  EEPROM.put(address, systemState.averagePostureScore);
  address += sizeof(systemState.averagePostureScore);

  EEPROM.put(address, systemState.dailyWarnings);
  address += sizeof(systemState.dailyWarnings);

  // 保存时间戳
  unsigned long timestamp = millis();
  EEPROM.put(address, timestamp);

  EEPROM.commit();
}

void loadHistoryData()
{
  int address = 0;

  unsigned long savedStudyTime;
  EEPROM.get(address, savedStudyTime);
  address += sizeof(savedStudyTime);

  int savedWarnings;
  EEPROM.get(address, savedWarnings);
  address += sizeof(savedWarnings);

  float savedAverageScore;
  EEPROM.get(address, savedAverageScore);
  address += sizeof(savedAverageScore);

  int savedDailyWarnings;
  EEPROM.get(address, savedDailyWarnings);
  address += sizeof(savedDailyWarnings);

  unsigned long savedTimestamp;
  EEPROM.get(address, savedTimestamp);

  // 如果数据有效，恢复历史统计
  if (savedTimestamp > 0 && savedTimestamp < millis())
  {
    systemState.totalStudyTime = savedStudyTime;
    systemState.averagePostureScore = savedAverageScore;
    systemState.dailyWarnings = savedDailyWarnings;
    systemState.totalSessions++;
  }
}

String generateSessionReport()
{
  unsigned long sessionTime = (millis() - systemState.sessionStartTime) / 60000;

  String report = "{";
  report += "\"type\":\"session_report\",";
  report += "\"session_time\":" + String(sessionTime) + ",";
  report += "\"posture_warnings\":" + String(systemState.postureWarnings) + ",";
  report += "\"average_score\":" + String(systemState.averagePostureScore, 1) + ",";
  report += "\"current_posture\":\"" + systemState.postureStatus + "\",";
  report += "\"distance\":" + String(systemState.currentDistance, 1) + ",";
  report += "\"voice_interactions\":" + String(voiceCache.interactionCount) + ",";
  report += "\"timestamp\":" + String(millis()) + ",";
  report += "\"date\":\"" + getCurrentDateString() + "\",";
  report += "\"recommendations\":\"" + generateAIRecommendations() + "\"";
  report += "}";

  return report;
}

String generateAIRecommendations()
{
  String recommendations = "";

  if (systemState.averagePostureScore >= 90)
  {
    recommendations = "坐姿优秀，请继续保持良好习惯。建议定时休息，保持学习节奏。";
  }
  else if (systemState.averagePostureScore >= 70)
  {
    recommendations = "坐姿总体良好，建议更加注意距离控制和背部挺直。";
  }
  else if (systemState.averagePostureScore >= 50)
  {
    recommendations = "坐姿需要改进，建议调整座椅高度和距离，并加强坐姿自我监控。";
  }
  else
  {
    recommendations = "坐姿问题较多，强烈建议重新调整学习环境，并培养良好的坐姿习惯。";
  }

  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;
  if (studyTime > 120)
  {
    recommendations += "学习时间较长，建议适当休息，避免长时间疲劳学习。";
  }

  return recommendations;
}

// ========== 微信小程序通信 ==========
void connectToWeChatMiniProgram()
{
  if (!systemState.wifiConnected)
    return;

  Serial.println("📱 连接微信小程序服务...");

  // 这里应该是WebSocket连接到微信小程序后端
  // webSocket.begin("your-websocket-server.com", 80, "/smartdesk");
  // webSocket.onEvent(webSocketEvent);

  Serial.println("✅ 微信小程序连接就绪");
}

void handleWiFiCommunication()
{
  if (!systemState.wifiConnected)
    return;

  // 处理WebSocket消息
  // webSocket.loop();

  // 检查串口WiFi模块消息
  if (wifiSerial.available())
  {
    String message = wifiSerial.readString();
    message.trim();

    if (message.startsWith("WECHAT:"))
    {
      handleWeChatMessage(message.substring(7));
    }
    else if (message.startsWith("VOICE:"))
    {
      handleWeChatVoiceMessage(message.substring(6));
    }
  }
}

void handleWeChatMessage(String message)
{
  Serial.println("📱 收到小程序消息: " + message);

  if (message == "GET_STATUS")
  {
    sendStatusToWeChat();
  }
  else if (message == "GET_HISTORY")
  {
    sendHistoryToWeChat();
  }
  else if (message.startsWith("SET_CONFIG:"))
  {
    handleConfigUpdate(message.substring(11));
  }
  else if (message == "REQUEST_ANALYSIS")
  {
    sendDetailedAnalysisToWeChat();
  }
}

void handleWeChatVoiceMessage(String voiceCommand)
{
  Serial.println("🎤 小程序语音: " + voiceCommand);

  // 处理来自小程序的语音指令
  processVoiceCommand(voiceCommand);
}

void sendPostureAlertToWeChat(String status, float distance, String suggestion)
{
  if (!systemState.wifiConnected)
    return;

  String alert = "{";
  alert += "\"type\":\"posture_alert\",";
  alert += "\"status\":\"" + status + "\",";
  alert += "\"distance\":" + String(distance, 1) + ",";
  alert += "\"suggestion\":\"" + suggestion + "\",";
  alert += "\"timestamp\":\"" + getCurrentTimeString() + "\",";
  alert += "\"warning_count\":" + String(systemState.postureWarnings);
  alert += "}";

  wifiSerial.println("SEND:" + alert);
  Serial.println("📱 发送坐姿警告到小程序");
}

void sendVoiceInteractionToWeChat(String question, String response)
{
  if (!systemState.wifiConnected)
    return;

  String interaction = "{";
  interaction += "\"type\":\"voice_interaction\",";
  interaction += "\"question\":\"" + question + "\",";
  interaction += "\"response\":\"" + response + "\",";
  interaction += "\"timestamp\":\"" + getCurrentTimeString() + "\"";
  interaction += "}";

  wifiSerial.println("SEND:" + interaction);
}

void sendHourlyReminderToWeChat()
{
  if (!systemState.wifiConnected)
    return;

  String reminder = "{";
  reminder += "\"type\":\"hourly_reminder\",";
  reminder += "\"time\":\"" + getCurrentTimeString() + "\",";
  reminder += "\"study_time\":" + String((millis() - systemState.sessionStartTime) / 60000) + ",";
  reminder += "\"posture_score\":" + String(systemState.averagePostureScore, 1) + ",";
  reminder += "\"warnings_today\":" + String(systemState.dailyWarnings);
  reminder += "}";

  wifiSerial.println("SEND:" + reminder);
}

void sendSessionDataToWeChat(String sessionReport)
{
  wifiSerial.println("SEND:" + sessionReport);
  Serial.println("📱 发送会话数据到小程序");
}

void syncWithWeChatMiniProgram()
{
  if (!systemState.wifiConnected)
    return;

  Serial.println("📱 同步数据到微信小程序");

  // 发送完整状态
  sendStatusToWeChat();

  // 发送历史数据
  sendHistoryToWeChat();

  // 发送AI分析报告
  sendDetailedAnalysisToWeChat();
}

void sendStatusToWeChat()
{
  String status = "{";
  status += "\"type\":\"current_status\",";
  status += "\"user_present\":" + String(systemState.isUserPresent ? "true" : "false") + ",";
  status += "\"distance\":" + String(systemState.currentDistance, 1) + ",";
  status += "\"posture\":\"" + systemState.postureStatus + "\",";
  status += "\"score\":" + String(systemState.averagePostureScore, 1) + ",";
  status += "\"warnings\":" + String(systemState.postureWarnings) + ",";
  status += "\"study_time\":" + String((millis() - systemState.sessionStartTime) / 60000) + ",";
  status += "\"wifi_connected\":" + String(systemState.wifiConnected ? "true" : "false") + ",";
  status += "\"timestamp\":\"" + getCurrentTimeString() + "\"";
  status += "}";

  wifiSerial.println("SEND:" + status);
}

void sendHistoryToWeChat()
{
  String history = "{\"type\":\"posture_history\",\"data\":[";

  for (int i = 0; i < 20; i++)
  {
    if (postureHistory[i].timestamp > 0)
    {
      if (i > 0)
        history += ",";
      history += "{";
      history += "\"distance\":" + String(postureHistory[i].distance, 1) + ",";
      history += "\"status\":\"" + postureHistory[i].status + "\",";
      history += "\"suggestion\":\"" + postureHistory[i].aiSuggestion + "\",";
      history += "\"score\":" + String(postureHistory[i].score, 1) + ",";
      history += "\"timestamp\":" + String(postureHistory[i].timestamp);
      history += "}";
    }
  }

  history += "]}";
  wifiSerial.println("SEND:" + history);
}

void sendDetailedAnalysisToWeChat()
{
  String analysis = "{";
  analysis += "\"type\":\"ai_analysis\",";
  analysis += "\"overall_assessment\":\"" + getOverallAssessment() + "\",";
  analysis += "\"improvement_suggestions\":\"" + getImprovementSuggestions() + "\",";
  analysis += "\"health_insights\":\"" + getHealthInsights() + "\",";
  analysis += "\"learning_efficiency\":\"" + getLearningEfficiencyAnalysis() + "\",";
  analysis += "\"timestamp\":\"" + getCurrentTimeString() + "\"";
  analysis += "}";

  wifiSerial.println("SEND:" + analysis);
}

// ========== AI分析报告生成 ==========
String getOverallAssessment()
{
  float score = systemState.averagePostureScore;
  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;

  if (score >= 90 && systemState.postureWarnings < 3)
  {
    return "优秀：您的学习习惯非常好，坐姿保持得很棒，请继续保持这种良好状态。";
  }
  else if (score >= 70 && systemState.postureWarnings < 5)
  {
    return "良好：整体表现不错，建议进一步优化坐姿细节，提升学习舒适度。";
  }
  else if (score >= 50)
  {
    return "一般：有改进空间，建议调整学习环境和坐姿习惯，注意定时休息。";
  }
  else
  {
    return "需要改进：坐姿问题较多，建议重新配置学习环境，培养健康的学习姿势。";
  }
}

String getImprovementSuggestions()
{
  String suggestions = "";

  if (systemState.currentDistance < IDEAL_DISTANCE_MIN)
  {
    suggestions += "距离太近，建议将座椅向后调整10-15厘米；";
  }
  else if (systemState.currentDistance > IDEAL_DISTANCE_MAX)
  {
    suggestions += "距离偏远，建议将座椅向前调整，保持合适距离；";
  }

  if (systemState.postureWarnings > 5)
  {
    suggestions += "坐姿警告较多，建议设置定时提醒，每30分钟调整一次姿势；";
  }

  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;
  if (studyTime > 90)
  {
    suggestions += "连续学习时间较长，建议适当休息，采用番茄钟学习法；";
  }

  if (suggestions == "")
  {
    suggestions = "当前状态良好，建议保持现有习惯，注意劳逸结合。";
  }

  return suggestions;
}

String getHealthInsights()
{
  return "根据WHO建议，长时间学习应保持正确坐姿，定时休息。" +
         "建议每30分钟站立活动3-5分钟，每小时远眺1-2分钟缓解眼疲劳。" +
         "良好的学习姿势有助于预防颈椎病、近视等问题。";
}

String getLearningEfficiencyAnalysis()
{
  float efficiency = calculateLearningEfficiency();

  if (efficiency >= 90)
  {
    return "学习效率高：坐姿稳定，注意力集中，建议保持当前节奏。";
  }
  else if (efficiency >= 70)
  {
    return "学习效率良好：有轻微分心，建议优化学习环境，减少干扰。";
  }
  else
  {
    return "学习效率有待提升：坐姿变化频繁，建议调整学习计划和环境。";
  }
}

float calculateLearningEfficiency()
{
  // 基于坐姿稳定性和警告频率计算学习效率
  float postureStability = systemState.averagePostureScore;
  float warningPenalty = systemState.postureWarnings * 5;
  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;

  float efficiency = postureStability - warningPenalty;
  if (studyTime > 0)
  {
    efficiency *= (1.0 - min(warningPenalty / studyTime, 0.5));
  }

  return max(0.0f, min(100.0f, efficiency));
}

// ========== 音频和显示系统 ==========
void playStartupMelody()
{
  Serial.println("🎵 播放开机音乐");
  int melody[] = {NOTE_C4, NOTE_E4, NOTE_G4, NOTE_C5, NOTE_E5};
  int durations[] = {200, 200, 200, 400, 600};

  for (int i = 0; i < 5; i++)
  {
    tone(BUZZER_PIN, melody[i], durations[i]);
    delay(durations[i] + 50);
    noTone(BUZZER_PIN);
  }
}

void playWarningBeep()
{
  for (int i = 0; i < 3; i++)
  {
    tone(BUZZER_PIN, 1000, 200);
    delay(300);
    noTone(BUZZER_PIN);
  }
}

void playHourlyChime()
{
  Serial.println("🔔 播放整点音乐");
  int melody[] = {NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_C5, NOTE_B4};
  int durations[] = {250, 250, 500, 500, 500, 1000};

  for (int i = 0; i < 6; i++)
  {
    tone(BUZZER_PIN, melody[i], durations[i]);
    delay(durations[i] + 100);
    noTone(BUZZER_PIN);
  }
}

void speakMessage(String message)
{
  if (!systemState.voiceEnabled)
    return;

  Serial.println("🔊 语音播报: " + message);

  // 这里应该调用TTS API或语音合成模块
  // 现在用蜂鸣器的不同音调来模拟语音
  int messageLength = message.length();
  for (int i = 0; i < min(messageLength / 10, 5); i++)
  {
    tone(BUZZER_PIN, 800 + i * 100, 100);
    delay(150);
    noTone(BUZZER_PIN);
  }
}

void updateMainDisplay()
{
  display.clearDisplay();

  // 标题栏
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("=== 智能学习桌 ===");

  // 状态指示
  display.setCursor(110, 0);
  if (systemState.wifiConnected)
  {
    display.println("WiFi");
  }
  else
  {
    display.println("----");
  }

  // 时间显示
  display.setCursor(0, 12);
  display.print("时间: ");
  display.println(getCurrentTimeString());

  // 距离和坐姿
  display.setCursor(0, 22);
  display.print("距离: ");
  if (systemState.currentDistance > 0)
  {
    display.print(systemState.currentDistance, 1);
    display.println(" cm");
  }
  else
  {
    display.println("-- cm");
  }

  display.setCursor(0, 32);
  display.print("坐姿: ");
  display.print(systemState.postureStatus);
  display.print(" (");
  display.print(systemState.averagePostureScore, 0);
  display.println(")");

  // 学习统计
  unsigned long studyMinutes = (millis() - systemState.sessionStartTime) / 60000;
  display.setCursor(0, 42);
  display.print("学习: ");
  display.print(studyMinutes);
  display.print("分 警告:");
  display.println(systemState.postureWarnings);

  // 状态栏
  display.setCursor(0, 52);
  if (systemState.isUserPresent)
  {
    display.print("在座 ");
  }
  else
  {
    display.print("离座 ");
  }

  if (voiceCache.interactionCount > 0)
  {
    display.print("AI:");
    display.print(voiceCache.interactionCount);
    display.print(" ");
  }

  // 效率指示
  float efficiency = calculateLearningEfficiency();
  display.print("效率:");
  display.print(efficiency, 0);
  display.println("%");

  display.display();
}

void updateTimeDisplay()
{
  systemState.currentTime = getCurrentTimeString();
  systemState.currentHour = getHour();
  systemState.currentMinute = getMinute();
}

void showBootScreen()
{
  display.clearDisplay();

  // Logo和标题
  display.setTextSize(2);
  display.setCursor(5, 5);
  display.println("AIOT");
  display.setCursor(0, 25);
  display.println("智能学习桌");

  display.setTextSize(1);
  display.setCursor(0, 45);
  display.println("系统启动中...");

  display.setCursor(0, 55);
  display.println("v2.0 完整功能版");

  display.display();
  delay(3000);
}

// ========== 按键和LED控制 ==========
void handleButtonInputs()
{
  static bool lastFuncState = HIGH;
  static bool lastCalibState = HIGH;
  static bool lastResetState = HIGH;
  static unsigned long lastDebounceTime = 0;

  bool currentFuncState = digitalRead(BUTTON_FUNC_PIN);
  bool currentCalibState = digitalRead(BUTTON_CALIB_PIN);
  bool currentResetState = digitalRead(BUTTON_RESET_PIN);

  unsigned long currentTime = millis();

  // 功能按键
  if (currentFuncState != lastFuncState && (currentTime - lastDebounceTime) > 200)
  {
    if (currentFuncState == LOW)
    {
      handleFunctionButton();
      lastDebounceTime = currentTime;
    }
    lastFuncState = currentFuncState;
  }

  // 校准按键
  if (currentCalibState != lastCalibState && (currentTime - lastDebounceTime) > 200)
  {
    if (currentCalibState == LOW)
    {
      handleCalibrationButton();
      lastDebounceTime = currentTime;
    }
    lastCalibState = currentCalibState;
  }

  // 复位按键
  if (currentResetState != lastResetState && (currentTime - lastDebounceTime) > 200)
  {
    if (currentResetState == LOW)
    {
      handleResetButton();
      lastDebounceTime = currentTime;
    }
    lastResetState = currentResetState;
  }
}

void handleFunctionButton()
{
  static int functionMode = 0;
  functionMode = (functionMode + 1) % 4;

  Serial.println("🔘 功能按键按下 - 模式: " + String(functionMode));

  switch (functionMode)
  {
  case 0:
    speakMessage("显示当前状态");
    sendStatusToWeChat();
    break;
  case 1:
    speakMessage("执行坐姿检测");
    performPostureAnalysis();
    break;
  case 2:
    speakMessage("语音功能" + String(systemState.voiceEnabled ? "关闭" : "开启"));
    systemState.voiceEnabled = !systemState.voiceEnabled;
    break;
  case 3:
    speakMessage("发送数据到小程序");
    syncWithWeChatMiniProgram();
    break;
  }

  setLEDStatus("button_pressed");
  delay(200);
}

void handleCalibrationButton()
{
  Serial.println("🔘 校准按键按下");

  speakMessage("开始距离校准，请保持最佳坐姿");

  // 执行校准
  float calibrationDistance = measureUltrasonicDistance();
  if (calibrationDistance > 0)
  {
    // 这里可以调整理想距离范围
    speakMessage("校准完成，最佳距离为" + String(calibrationDistance, 1) + "厘米");
    Serial.println("📏 校准距离: " + String(calibrationDistance, 1) + "cm");
  }
  else
  {
    speakMessage("校准失败，请重试");
  }

  setLEDStatus("calibration");
  delay(200);
}

void handleResetButton()
{
  Serial.println("🔘 复位按键按下");

  speakMessage("重置系统数据");

  // 重置统计数据
  systemState.postureWarnings = 0;
  systemState.sessionStartTime = millis();
  systemState.dailyWarnings = 0;
  voiceCache.interactionCount = 0;

  // 清空历史记录
  for (int i = 0; i < 20; i++)
  {
    postureHistory[i].timestamp = 0;
  }

  speakMessage("系统数据已重置");
  setLEDStatus("reset");
  delay(200);
}

void setLEDStatus(String status)
{
  // 关闭所有LED
  digitalWrite(LED_RED_PIN, LOW);
  digitalWrite(LED_GREEN_PIN, LOW);
  digitalWrite(LED_BLUE_PIN, LOW);

  if (status == "ready" || status == "good")
  {
    digitalWrite(LED_GREEN_PIN, HIGH);
  }
  else if (status == "warning" || status == "camera_warning")
  {
    digitalWrite(LED_RED_PIN, HIGH);
  }
  else if (status == "wifi_connected")
  {
    digitalWrite(LED_BLUE_PIN, HIGH);
  }
  else if (status == "button_pressed")
  {
    digitalWrite(LED_GREEN_PIN, HIGH);
    digitalWrite(LED_BLUE_PIN, HIGH);
  }
  else if (status == "calibration")
  {
    digitalWrite(LED_RED_PIN, HIGH);
    digitalWrite(LED_GREEN_PIN, HIGH);
  }
  else if (status == "reset")
  {
    digitalWrite(LED_RED_PIN, HIGH);
    digitalWrite(LED_GREEN_PIN, HIGH);
    digitalWrite(LED_BLUE_PIN, HIGH);
  }
}

void blinkLEDs()
{
  for (int i = 0; i < 3; i++)
  {
    setLEDStatus("reset");
    delay(200);
    setLEDStatus("ready");
    delay(200);
  }
}

// ========== 环境光线控制 ==========
void handleLightingControl()
{
  static unsigned long lastLightCheck = 0;

  if (millis() - lastLightCheck >= 5000)
  { // 每5秒检查一次光线
    int lightLevel = analogRead(LIGHT_SENSOR_PIN);

    // 根据光线强度控制LED灯带
    if (lightLevel < 200)
    {                                // 光线较暗
      digitalWrite(RELAY_PIN, HIGH); // 开启LED灯带
    }
    else if (lightLevel > 800)
    {                               // 光线很亮
      digitalWrite(RELAY_PIN, LOW); // 关闭LED灯带
    }

    lastLightCheck = millis();
  }
}

// ========== 时间工具函数 ==========
String getCurrentTimeString()
{
  time_t now = time(nullptr);
  struct tm *timeinfo = localtime(&now);

  char timeStr[20];
  strftime(timeStr, sizeof(timeStr), "%H:%M:%S", timeinfo);
  return String(timeStr);
}

String getCurrentDateString()
{
  time_t now = time(nullptr);
  struct tm *timeinfo = localtime(&now);

  char dateStr[20];
  strftime(dateStr, sizeof(dateStr), "%Y-%m-%d", timeinfo);
  return String(dateStr);
}

int getHour()
{
  time_t now = time(nullptr);
  struct tm *timeinfo = localtime(&now);
  return timeinfo->tm_hour;
}

int getMinute()
{
  time_t now = time(nullptr);
  struct tm *timeinfo = localtime(&now);
  return timeinfo->tm_min;
}

// ========== 系统关机和清理 ==========
void systemShutdown()
{
  Serial.println("🔄 系统正在关机...");

  speakMessage("智能学习桌系统正在关机，正在保存数据");

  // 最终数据保存
  saveSessionData();

  // 发送关机报告到微信小程序
  sendShutdownReportToWeChat();

  // 显示关机界面
  showShutdownScreen();

  // 播放关机音乐
  playShutdownMelody();

  // 关闭所有外设
  digitalWrite(LED_RED_PIN, LOW);
  digitalWrite(LED_GREEN_PIN, LOW);
  digitalWrite(LED_BLUE_PIN, LOW);
  digitalWrite(RELAY_PIN, LOW);

  display.clearDisplay();
  display.display();

  speakMessage("再见，期待下次使用");

  Serial.println("✅ 系统关机完成");
}

void sendShutdownReportToWeChat()
{
  if (!systemState.wifiConnected)
    return;

  unsigned long totalTime = (millis() - systemState.sessionStartTime) / 60000;

  String shutdownReport = "{";
  shutdownReport += "\"type\":\"shutdown_report\",";
  shutdownReport += "\"total_study_time\":" + String(totalTime) + ",";
  shutdownReport += "\"total_warnings\":" + String(systemState.postureWarnings) + ",";
  shutdownReport += "\"average_score\":" + String(systemState.averagePostureScore, 1) + ",";
  shutdownReport += "\"voice_interactions\":" + String(voiceCache.interactionCount) + ",";
  shutdownReport += "\"efficiency_score\":" + String(calculateLearningEfficiency(), 1) + ",";
  shutdownReport += "\"final_assessment\":\"" + getOverallAssessment() + "\",";
  shutdownReport += "\"shutdown_time\":\"" + getCurrentTimeString() + "\"";
  shutdownReport += "}";

  wifiSerial.println("SEND:" + shutdownReport);
  delay(1000); // 等待发送完成
}

void showShutdownScreen()
{
  display.clearDisplay();

  display.setTextSize(2);
  display.setCursor(20, 10);
  display.println("再见!");

  display.setTextSize(1);
  display.setCursor(0, 35);
  display.println("数据已保存");

  unsigned long studyTime = (millis() - systemState.sessionStartTime) / 60000;
  display.setCursor(0, 45);
  display.print("本次学习: ");
  display.print(studyTime);
  display.println("分钟");

  display.setCursor(0, 55);
  display.println("感谢使用智能学习桌");

  display.display();
  delay(3000);
}

void playShutdownMelody()
{
  int melody[] = {NOTE_C5, NOTE_A4, NOTE_F4, NOTE_C4};
  int durations[] = {300, 300, 400, 800};

  for (int i = 0; i < 4; i++)
  {
    tone(BUZZER_PIN, melody[i], durations[i]);
    delay(durations[i] + 100);
    noTone(BUZZER_PIN);
  }
}

// ========== 配置更新处理 ==========
void handleConfigUpdate(String config)
{
  // 处理来自小程序的配置更新
  if (config.indexOf("voice_enabled") >= 0)
  {
    systemState.voiceEnabled = config.indexOf("true") >= 0;
    speakMessage("语音功能已" + String(systemState.voiceEnabled ? "开启" : "关闭"));
  }
  else if (config.indexOf("camera_enabled") >= 0)
  {
    systemState.cameraEnabled = config.indexOf("true") >= 0;
    speakMessage("摄像头检测已" + String(systemState.cameraEnabled ? "开启" : "关闭"));
  }

  Serial.println("⚙️ 配置更新: " + config);
}

// ========== 主程序结束 ==========
}